package controller.ur;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import controller.CUtil;

import model.dao.UserDaoLocal;
import model.entity.Album;
import model.entity.Photo;
import model.entity.User;

/**
 * Servlet implementation class SAuthorsRSS
 */
public class SAuthorsRSS extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@EJB
	private UserDaoLocal userDao;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SAuthorsRSS() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(!CUtil.checkLogIn(request, response))
			return;
		
		User currentUser=userDao.findById(Integer.parseInt((String)request.getParameter("userId")));
		
		response.setContentType("application/rss+xml");
		PrintWriter writer=response.getWriter();
		String serv=request.getServerName()+":"+request.getServerPort()+request.getContextPath();
		String start="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
					+"<rss version=\"2.0\">"
					+"<channel>"
					+"<title>Epics</title>"
					+"<link>"+serv+"</link>"
					+"<description>Epics mbs2 project</description>";
		writer.write(start);
		
		List<Photo> photos=new ArrayList<Photo>();
		for(Album a:currentUser.getAlbums()){
			if(!a.getFavorite()){
				for(Photo photo:a.getPhotos()){
					if(photo.getPub()){
						photos.add(photo);
					}
				}
			}
		}
		Collections.sort(photos, new Comparator<Photo>() {
			public int compare(Photo p1, Photo p2)
            {
                return p1.getUploadDate().compareTo(p2.getUploadDate());
            } 
		});
		
		for(Photo photo:photos){
			String item="<item>"
					+"<title>"+photo.getTitle()+"</title>"
					+"<link>"+serv+"/SViewPhoto?photoId="+photo.getId()+"</link>"
					+"<description>"+photo.getDescription()+"</description>"
					+"</item>";
			writer.write(item);
		}
		
		String end="</channel>"
					+"</rss>";
		writer.write(end);
		writer.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
